import { clear, isAuthorized, setToken } from "@/utils/userInfoUtils";
import {
  BackgroundImage,
  Box,
  Button,
  Container,
  Divider,
  Group,
  Image,
  Paper,
  Stack,
  Text,
} from "@mantine/core";
import { useForm } from "@mantine/form";
import { notifications } from "@mantine/notifications";
import { useEffect } from "react";

import { useAPIUtils } from "@/components/APIUtilsProvider";
import { Anchor, PasswordInput, TextInput } from "@mantine/core";
import { useNavigate } from "react-router-dom";

function Login() {
  const { baseUrl } = useAPIUtils();

  const navigate = useNavigate();

  useEffect(() => {
    isAuthorized().then((authorized) => {
      if (authorized) {
        navigate("/");
      }
    });
  }, []);

  const doLogin = async ({ username, password }) => {
    await clear();

    const url = new URL(`/api/login`, baseUrl);
    console.log("url", url);
    url.search = new URLSearchParams({ username, password });

    const res = await fetch(url, {
      method: "POST",
    });

    if (!res.ok) {
      const { message } = await res.json();
      notifications.show({
        color: "red",
        title: "登录失败",
        message: message,
      });
      throw new Error("登录失败");
    } else {
      const { token, expiration } = await res.json();
      await setToken({ token, expiration });
      notifications.show({
        title: "登录成功",
      });
      navigate("/");
    }
  };

  const form = useForm({
    initialValues: {
      username: "",
      password: "",
    },

    validate: {
      username: (value) => (value.length > 0 ? null : "用户名不能为空"),
      password: (value) => (value.length > 0 ? null : "密码不能为空"),
    },
  });

  return (
    <Box>
      <BackgroundImage h={"100vh"} src="/soft-gradiant.png">
        <Stack align="center" justify="center" h={"100vh"}>
          <Paper
            radius="24"
            style={{
              height: 800,
              width: 1200,
              padding: 16,
              boxShadow:
                "rgba(0, 0, 0, 0.05) 0px 1px 3px 0px, rgba(0, 0, 0, 0.05) 0px 36px 28px -7px, rgba(0, 0, 0, 0.04) 0px 17px 17px",
            }}
          >
            <Group justify="space-between">
              <Image src={"/cover.webp"} w="auto" h={800 - 32} radius={24} />
              <Container h={800 - 32}>
                <Group mt={160} justify="center" gap={"4"}>
                  <Image src={"/joymart.png"} w={32} h={32} />
                  <Text size="xl" fw={600} ta="center">
                    良品至信运营平台
                  </Text>
                </Group>

                <Divider label="请登录" labelPosition="center" my="lg" />

                <form onSubmit={form.onSubmit((values) => doLogin(values))}>
                  <Stack>
                    <TextInput
                      label="用户名"
                      placeholder="请输入用户名"
                      radius="md"
                      {...form.getInputProps("username")}
                    />

                    <PasswordInput
                      label="密码"
                      placeholder="请输入密码"
                      {...form.getInputProps("password")}
                      radius="md"
                    />
                  </Stack>

                  <Group justify="end" mt="xl">
                    <Anchor
                      component="button"
                      type="button"
                      c="dimmed"
                      onClick={() => toggle()}
                      size="xs"
                    >
                      忘记密码
                    </Anchor>
                    <Button type="submit" color="black" size="md" radius="xl">
                      登 录
                    </Button>
                  </Group>
                </form>
              </Container>
            </Group>
          </Paper>
          <Text c="dimmed">All rights reserved.</Text>
        </Stack>
      </BackgroundImage>
    </Box>
  );
}

export default Login;
